package com.lnkwe.controller;

import com.alibaba.fastjson.JSONObject;
import com.lnkwe.config.BaseConfig;
import com.lnkwe.core.db.DbIdGenerator;
import com.lnkwe.sys.model.SysAtt;
import com.lnkwe.sys.service.SysAttService;
import com.lnkwe.util.FileUploadUtil;
import com.lnkwe.util.UserUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by lijing on 2016-03-17.
 */

@Controller
@RequestMapping("/")
public class UploaderController {
    private Logger logger = Logger.getLogger(UploaderController.class);

    @Autowired
    private SysAttService sysAttService;
    @Autowired
    private BaseConfig baseConfig;

    //上传附件
    @RequestMapping(value = "/upload")
    public void upload(@RequestParam String id, @RequestParam String key, HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        PrintWriter pw = null;
        try {

            response.setContentType("application/json; charset=utf-8");
            pw = response.getWriter();

            jsonObject = new JSONObject();
            jsonObject = FileUploadUtil.getInstance().upload(request, baseConfig);
            System.out.println("json:"+jsonObject.toJSONString());
            //jsonObject= FileUtil.getInstance().upload(request,baseConfig);
            SysAtt model = new SysAtt();
            model.setId(DbIdGenerator.generateID());
            model.setModelId(id);
            model.setModelName(key);
            model.setFileSize(jsonObject.getDouble("size"));
            model.setName(jsonObject.getString("file"));
            model.setFullPath(jsonObject.getString("url"));
            model.setUploadPath(jsonObject.getString("uploadFile"));
            model.setCreateTime(new Date());
            model.setCreatorId(UserUtil.getSysUserId(request));
            sysAttService.save(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.print(jsonObject.toString());

    }
}
